<template>
  <div class="useHelp">
    <div class="container">
      <div class="search-card">
        <div class="search-argument">
          <!-- 标题 -->
          <div class="search-item">
            <span class="labelName">{{ $t("publicInfo.HelpTitle") }}</span>
            <el-input
              clearable
              v-model="params.helpTitle"
              class="search-input"
              maxlength="20"
              :placeholder="$t('placeholder.HelpTitle')"
            ></el-input>
          </div>
          <!-- 搜索按钮 -->
          <div class="search-button">
            <div class="btn search" @click="getHelpList">
              <el-icon class="icon" color="#fff"> <Search /> </el-icon
              >{{ $t("common.search") }}
            </div>
            <div class="btn reset" @click="resetSearch">
              <el-icon class="icon" color="rgba(43, 193, 123, 1)">
                <Refresh /> </el-icon
              >{{ $t("common.reset") }}
            </div>
          </div>
        </div>
        <div class="batch-operation">
          <el-button
            class="btn search"
            @click="openFormDialog('add')"
            v-hasPermi="['publicInfo:useHelp:add']"
          >
            <el-icon class="icon"> <Plus /> </el-icon
            >{{ $t("publicInfo.AddHelp") }}
          </el-button>
          <el-button
            v-if="deleteIds.length > 0"
            class="btn remove"
            @click="deletePrompt()"
            v-hasPermi="['publicInfo:useHelp:remove']"
          >
            <el-icon class="icon"> <Delete /> </el-icon
            >{{ $t("common.BatchDeletion") }}
          </el-button>
          <el-button
            v-else
            class="btn cantUse"
            v-hasPermi="['publicInfo:useHelp:remove']"
          >
            <el-icon class="icon"> <Delete /> </el-icon
            >{{ $t("common.BatchDeletion") }}
          </el-button>
        </div>
      </div>

      <!-- 表格数据 -->
      <el-table
        v-loading="loading"
        :data="helpList"
        :border="true"
        max-height="60vh"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column
          type="index"
          :label="$t('publicInfo.SerialNo')"
          :index="indexMethod"
          width="85"
          align="center"
        />
        <el-table-column
          :label="$t('publicInfo.Operate')"
          align="center"
          min-width="120"
          class-name="small-padding fixed-width"
        >
          <template #default="{ row }">
            <el-button
              link
              type="primary"
              @click="openFormDialog('detail', row.helpId)"
              v-hasPermi="['publicInfo:useHelp:detail']"
              >{{ $t("common.detail") }}</el-button
            >
            <el-button
              link
              type="primary"
              @click="openFormDialog('edit', row.helpId)"
              v-hasPermi="['publicInfo:useHelp:edit']"
              >{{ $t("common.edit") }}</el-button
            >
            <el-button
              link
              type="danger"
              @click="deletePrompt(row.helpId)"
              v-hasPermi="['publicInfo:useHelp:remove']"
              >{{ $t("common.delete") }}</el-button
            >
          </template>
        </el-table-column>
        <el-table-column
          :label="$t('publicInfo.HelpTitle')"
          prop="title"
          :show-overflow-tooltip="true"
          min-width="85"
          align="center"
        />
        <el-table-column
          :label="$t('publicInfo.File')"
          :show-overflow-tooltip="true"
          min-width="85"
          align="center"
        >
          <template #default="{ row }">
            <span>{{
              row.file ? `${row.file.fileName}.${row.file.fileExtension}` : "-"
            }}</span>
          </template>
        </el-table-column>
        <el-table-column
          :label="$t('publicInfo.UpdateTime')"
          align="center"
          min-width="150"
        >
          <template #default="{ row }">
            <span>{{ row.updateTime }}</span>
          </template>
        </el-table-column>
        <el-table-column
          :label="$t('publicInfo.ReleaseTime')"
          align="center"
          min-width="150"
        >
          <template #default="{ row }">
            <span>{{ row.publishTime }}</span>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="params.pageNum"
        v-model:limit="params.pageSize"
        @pagination="getHelpList"
        class="pagination"
      />

      <!-- 新增弹出层 -->
      <el-dialog
        v-model="addNewVisible"
        @close="closeDialog"
        :title="formTitle"
        :close-on-click-modal="false"
        class="add-dialog"
      >
        <el-form
          label-width="100px"
          ref="helpFormRef"
          :model="helpForm"
          :rules="rules"
        >
          <el-form-item :label="$t('publicInfo.HelpTitle')" prop="title">
            <el-input
              :disabled="isDisabled"
              v-model="helpForm.title"
              maxlength="20"
              :placeholder="$t('placeholder.HelpTitle')"
            />
          </el-form-item>
          <el-form-item :label="$t('publicInfo.HelpFile')" prop="file">
            <Upload
              :fileList="fileList"
              :isCanDelete="isCanDelete"
              :isFull="true"
              :showButton="showButton"
              @success="uploadSuccess"
              @deleteFile="deleteFile"
            />
          </el-form-item>
          <el-form-item :label="$t('publicInfo.Remark')">
            <el-input
              :disabled="isDisabled"
              v-model="helpForm.remark"
              :placeholder="$t('placeholder.remark')"
              maxlength="150"
              :rows="3"
              type="textarea"
            />
          </el-form-item>
          <div class="dialogFoot">
            <div class="btn delete" @click="closeDialog">
              {{ isDisabled ? $t("common.close") : $t("common.cancel") }}
            </div>
            <div
              v-if="!isDisabled"
              class="btn search"
              @click="submit(helpFormRef)"
            >
              {{ $t("common.confirm") }}
            </div>
          </div>
        </el-form>
      </el-dialog>

      <!-- 删除弹出层 -->
      <el-dialog v-model="deleteVisible" class="no-header-dialog">
        <img src="@/assets/images/warn.png" alt="" />
        <div class="dec">
          确定删除选中的 <span class="deletecolor">帮助</span> 吗？
        </div>
        <div class="chooise">
          <div class="btn delete" @click="closeDelete">
            {{ $t("common.cancel") }}
          </div>
          <div class="btn success" @click="deleteApply">
            {{ $t("common.confirm") }}
          </div>
        </div>
      </el-dialog>
    </div>
  </div>
</template>
<script>
export default {
  name: "UseHelp",
};
</script>
<script setup>
import { onMounted, reactive, ref } from "vue";
import dayjs from "dayjs";
import { ElMessage } from "element-plus";
import {
  getHelpListApi,
  deleteHelpApi,
  getHelpDetailApi,
  saveHelpApi,
  updateHelpApi,
} from "@/api/publickInfo/help";
import Upload from "@/components/Upload/index";
import { deleteFiles } from "@/api/upload";
import { getCurrentInstance } from "vue";

const { $t } = getCurrentInstance().proxy;
const loading = ref(false);
const helpList = ref([]);
const addNewVisible = ref(false);
const deleteVisible = ref(false);
const helpFormRef = ref();
// 请求参数
const params = reactive({
  helpTitle: null,
  pageNum: 1,
  pageSize: 10,
});
const total = ref(0);
const fileList = ref([]);
const showButton = ref(true);
const isCanDelete = ref(true);
const deleteIds = ref([]);
const deleteId = ref();

const isDisabled = computed(() => {
  return formTitle.value === $t("publicInfo.HelpDetail");
});

// -------------------------------------------------  获取列表数据  -----------------------------------------------------
/**
 * @获取列表
 */
const getHelpList = async () => {
  try {
    loading.value = true;
    const res = await getHelpListApi(params);
    helpList.value = res.rows;
    total.value = res.total;
    loading.value = false;
  } catch (error) {
    loading.value = false;
  }
};

/**
 * @重置搜索参数
 */
const resetSearch = () => {
  params.helpTitle = null;
  params.pageNum = 1;
  params.pageSize = 10;
  getHelpList();
};

/**
 * @文件上传成功回调函数
 */
const uploadSuccess = (data) => {
  fileList.value.push(data);
  helpFormRef.value.validateField();
};

/**
 * @删除上传文件回调函数
 */
const deleteFile = async (index, fileId) => {
  fileList.value.splice(index, 1);
  if (fileId) {
    const res = await deleteFiles(fileId);
    if (res.code === 200) ElMessage.success("文件已成功删除！");
  }
};

/**
 * @监听上传文件
 */
watch(fileList.value, (newV, oldV) => {
  if (fileList.value.length > 0) {
    showButton.value = false;
    helpForm.value.file = fileList.value[0];
  } else {
    showButton.value = true;
    helpForm.value.file = {};
  }
});

// -------------------------------------------------  表单事件  -----------------------------------------------------
/**
 * @表单对象
 * */
const helpForm = ref(initForm());

/**
 * @表单校验规则
 * */
const rules = reactive({
  title: [{ required: true, message: "请输入帮助标题", trigger: "blur" }],
  file: [
    {
      required: true,
      validator: (rule, value, callback) => {
        if (!value.url) {
          callback(new Error("请上传帮助文件"));
        }
        callback();
      },
    },
  ],
});

/**
 * @初始化表单
 * */
function initForm() {
  return {
    title: null,
    file: {},
    publishTime: null,
    remark: null,
  };
}

/**
 * @提交表单
 * */
const submit = async (formEl) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      let res = null;
      if (helpForm.value.helpId) {
        res = await updateHelpApi({
          ...helpForm.value,
        });
      } else {
        let publishTime = dayjs().format("YYYY-MM-DD HH:mm:ss");
        res = await saveHelpApi({
          ...helpForm.value,
          publishTime,
        });
      }
      if (res.code === 200) ElMessage.success(res.msg);
      else ElMessage.error(res.msg);
      await getHelpList();
      addNewVisible.value = false;
      helpForm.value = initForm();
      deleteFile(0);
    } else {
      console.log("error submit!", fields);
    }
  });
};

// -------------------------------------------------  删除事件  -----------------------------------------------------
const deletePrompt = (id) => {
  deleteVisible.value = true;
  if (id) deleteId.value = id;
};

const closeDelete = () => {
  deleteVisible.value = false;
  deleteId.value = null;
};

const deleteApply = async () => {
  let ids = deleteId.value || deleteIds.value;
  const res = await deleteHelpApi(ids);
  if (res.code === 200) ElMessage.success(res.msg);
  else ElMessage.error(res.msg);
  await getHelpList();
  deleteVisible.value = false;
  deleteIds.value = [];
  deleteId.value = null;
};
function handleSelectionChange(selection) {
  deleteIds.value = selection.map((item) => item.helpId);
}

// -------------------------------------------------  弹出层事件  -----------------------------------------------------
const formTitle = ref("");
/**
 * @打开表单弹出层
 * @openType 打开弹出层的操作类型，根据不同类型修改弹出层标题
 * */
const openFormDialog = async (openType, id) => {
  addNewVisible.value = true;
  if (openType === "add") formTitle.value = $t("publicInfo.AddHelp");
  if (openType === "edit") {
    formTitle.value = $t("publicInfo.EditHelp");
    const { data } = await getHelpDetailApi(id);
    if (data.file.url) fileList.value.push(data.file);
    helpForm.value = data;
  }
  if (openType === "detail") {
    formTitle.value = $t("publicInfo.HelpDetail");
    isCanDelete.value = false;
    const { data } = await getHelpDetailApi(id);
    if (data.file.url) fileList.value.push(data.file);
    helpForm.value = data;
    if (!data.remark) helpForm.value.remark = "暂无数据";
  }
};

/**
 * @关闭详情表单弹出层
 * */
const closeDialog = () => {
  addNewVisible.value = false;
  isCanDelete.value = true;
  helpForm.value = initForm();
  deleteFile(0);
};

// -----------------------------------  序号  ----------------------------------
function indexMethod(index) {
  // 当前页码
  const currentPage = params.pageNum;
  // 每页显示的数据条数
  const pageSize = params.pageSize;
  // 当前行的实际索引
  const truelndex = (currentPage - 1) * pageSize + index + 1;
  // 如果当前行的索引大于等于当前页的最大索引，
  // 则使用当前行的实际索引，否则使用当前行的原始索引
  return truelndex;
}

onMounted(() => {
  getHelpList();
});
</script>

<style lang="scss">
.useHelp {
  .search-item .search-input .el-input,
  .search-time .el-date-editor {
    height: 40px !important;
  }

  .add-dialog .el-dialog__body {
    padding: 20px 40px 20px 20px;

    .createBtn {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 10px 26px;
      width: 98px;
      height: 36px;
      font-size: 12px;
      box-sizing: border-box;
      border-radius: 4px;
      color: rgba(43, 193, 123, 1);
      background: rgba(51, 151, 255, 0.03);
      border: 1px solid rgba(43, 193, 123, 1);
      cursor: pointer;
      &:hover {
        background: rgba(51, 151, 255, 0.1);
      }
    }

    .dialogFoot {
      width: 100%;
      height: 60px;
      line-height: 60px;
      text-align: center;
      // margin: 20px 0;
      display: flex;
      justify-content: center;
      align-items: center;
      .btn {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 81px;
        height: 32px;
        padding: 10px;
        margin-right: 14px;
        font-size: 14px;
        border-radius: 4px;
        user-select: none;
        border: 1px solid rgba(220, 223, 230, 1);
        cursor: pointer;
        &:hover {
          background: rgba(0, 0, 0, 0.1);
        }
      }
      .btn.search {
        color: #fff;
        background: rgba(43, 193, 123, 1);
        border: 1px solid rgba(43, 193, 123, 1);
        &:hover {
          background: rgba(43, 193, 123, 0.85);
        }
      }
    }
  }
}
</style>

<style scoped lang="scss">
.useHelp {
  width: 100%;
  height: 100%;

  .container {
    position: relative;
    width: calc(100% - 40px);
    height: 92%;
    margin: 0 20px 20px;
    border-radius: 10px;
    background: white;

    .pagination {
      position: absolute;
      left: 50%;
      bottom: 30px;
      transform: translateX(-50%);
    }
  }

  .search-card {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    align-items: flex-start;
    padding: 30px 0;
    width: 100%;
    height: 100px;
    border-radius: 10px;
    background-color: #fff;
  }

  .search-argument {
    width: 100%;
    display: flex;
    flex-wrap: wrap;
    justify-content: flex-start;
    align-content: flex-start;
    gap: 20px;

    .search-item {
      display: flex;
      justify-content: flex-start;
      align-items: center;
      width: 24%;
      height: 40px;

      .search-input {
        flex: 1;
        width: 270px;
        height: 40px;
      }
    }

    .labelName {
      display: inline-block;
      width: 80px;
      text-align: right;
      font-size: 14px;
      margin-right: 15px;
    }

    .search-button {
      position: absolute;
      right: 0px;
      top: -45px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      width: 160px;
      height: 40px;
    }
  }

  .batch-operation {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    position: absolute;
    right: 180px;
    top: -45px;
    height: 40px;
  }

  .tag {
    display: inline-block;
    width: 80px;
    height: 30px;
    line-height: 30px;
    text-align: center;
    border-radius: 15px;
    color: rgba(153, 153, 153, 1);
    border: 1px solid rgba(153, 153, 153, 1);
  }
  .tag.warning {
    color: rgba(255, 149, 18, 1);
    border: 1px solid rgba(255, 149, 18, 1);
  }
  .tag.success {
    color: rgba(43, 193, 123, 1);
    border: 1px solid rgba(43, 193, 123, 1);
  }

  .btn {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 34px;
    padding: 10px;
    font-size: 14px;
    border-radius: 4px;
    user-select: none;
    cursor: pointer;
  }
  .btn.search {
    color: #fff;
    background: rgba(43, 193, 123, 1);
    &:hover {
      background: rgba(43, 193, 123, 0.85);
    }
  }

  .btn.reset {
    color: rgba(43, 193, 123, 1);
    background: rgba(43, 193, 123, 0.05);
    border: 1px solid rgba(43, 193, 123, 1);
    &:hover {
      background: rgba(43, 193, 123, 0.2);
    }
  }

  .btn.remove {
    color: rgba(255, 149, 18, 1);
    background: rgba(255, 149, 18, 0.05);
    border: 1px solid rgba(255, 149, 18, 1);
    &:hover {
      background: rgba(255, 149, 18, 0.2);
    }
  }

  .btn.cantUse {
    color: rgba(255, 149, 18, 0.5);
    background: rgba(255, 149, 18, 0.05);
    border: 1px solid rgba(255, 149, 18, 0.5);
    cursor: not-allowed;
  }

  .icon {
    margin-right: 6px;
  }
}
</style>
